package org.libcsp.generic.util.lang;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class BeanUtil extends cn.hutool.core.bean.BeanUtil {

    public static <T> T copyPropertiesIgnoreCase(Object source, Object target) {
        Map<String, Field> sourceMap = CacheFieldMap.getFieldMap(source.getClass());
        CacheFieldMap.getFieldMap(target.getClass()).values().forEach((it) -> {
            Field field = sourceMap.get(it.getName().toLowerCase().replace("_", ""));
            if (field != null) {
                it.setAccessible(true);
                field.setAccessible(true);
                try {
                    //忽略null和空字符串
                    if (field.get(source) != null && StrUtil.isNotBlank(field.get(source).toString())) {
                        it.set(target, field.get(source));
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println(target.toString());
        return (T) target;
    }

    private static class CacheFieldMap {
        private static final Map<String, Map<String, Field>> cacheMap = new HashMap<>();

        private static synchronized Map<String, Field> getFieldMap(Class<?> clazz) {
            Map<String, Field> result = cacheMap.get(clazz.getName());
            if (result == null) {
                Map<String, Field> fieldMap = new HashMap<>();
                for (Field field : clazz.getDeclaredFields()) {
                    fieldMap.put(field.getName().toLowerCase().replace("_", ""), field);
                }
                cacheMap.put(clazz.getName(), fieldMap);
                result = cacheMap.get(clazz.getName());
            }
            return result;
        }
    }
}